<#assign fields=parm["fields"] >
<template>
  <!-- ******************************************************* -->
  <!-- 查询条件区域 -->
  <!-- ******************************************************* -->
  <div style="text-align:left">

    <el-form :inline="true" :model="queryParm">

<#list fields as item >
	<#if item.isQueryParm == '1'>
      <el-form-item label="${item.name}">
        <el-input v-model="queryParm.${item.columnName}" clearable />
      </el-form-item>
    </#if>
</#list>

      <el-form-item>
        <el-button type="primary" @click="onQuery">
          <el-icon style="margin-right: 6px;">
            <Search />
          </el-icon>
          {{ $t('common.query') }}
        </el-button>
      </el-form-item>
    </el-form>
  </div>

  <!-- ******************************************************* -->
  <!-- 操作按钮区域 -->
  <!-- ******************************************************* -->
  <div style="text-align:left; margin-bottom: 10px;">
    <el-button @click="onAdd($t('common.add'))">
      <el-icon style="margin-right: 6px;">
        <CirclePlus />
      </el-icon>
      {{ $t('common.add') }}
    </el-button>
    <el-button @click="onModify($t('common.modify'))" :disabled="!isSelectedRow">
      <el-icon style="margin-right: 6px;">
        <Edit />
      </el-icon>
      {{ $t('common.modify') }}
    </el-button>
    <el-button @click="onDelete" :disabled="!isSelectedRow">
      <el-icon style="margin-right: 6px;">
        <Delete />
      </el-icon>
      {{ $t('common.delete') }}
    </el-button>
    <el-button @click="onExportExcelFile">
      <el-icon style="margin-right: 6px;">
        <Download />
      </el-icon>
      {{ $t('common.export') }}
    </el-button>
  </div>

  <!-- ******************************************************* -->
  <!-- 数据列表区域 -->
  <!-- ******************************************************* -->
  <div class="dataArea">
    <el-table :data="tableData" height="100%" highlight-current-row @current-change="handleTableSelectRow"
      @row-dblclick="onModify($t('common.modify'))"
      style="width: 100%; font-size: 12px; border-radius: 4px; border: 1px solid #eee" :header-cell-style="{
        background: '#fafafa',
        color: '#333',
        fontWeight: '600',
        fontSize: '14px'
      }">
      <el-table-column type="index" width="50" />
      
<#list fields as item >
	<#if item.showInTable == '1'> 
      <el-table-column prop="${item.columnName}" label="${item.name}" <#if item?index < (fields?size - 1)>width="180"</#if>  />
	</#if>
</#list>
    </el-table>
  </div>

  <!-- ******************************************************* -->
  <!-- 分页列表区域 -->
  <!-- ******************************************************* -->
  <div class="paginationArea">
    <el-pagination background v-model:current-page="currentPage" v-model:page-size="pageSize" :total="totalRow"
      :page-sizes="[10, 20, 50, 100]" :small="false" :disabled="false" layout="total, prev, pager, next"
      @current-change="handleCurrentChange" @size-change="handleSizeChange" />
  </div>

  <!-- ******************************************************* -->
  <!-- 编辑弹窗区域 -->
  <!-- ******************************************************* -->
  <el-dialog v-model:model-value="editDialogVisible" width="30%" :before-close="editDialogHandleClose" destroy-on-close
    align-center>
    <editDialog ref="editDialogInstance" :editOpt='editDialogOptCmd' />

    <template #header>
      <div style="float: left;">
        {{ editDialogTitle }}
      </div>
    </template>

    <template #footer>
      <span class="dialog-footer">
        <el-button @click="editDialogVisible = false">
          {{ $t('common.cancel') }}
        </el-button>
        <el-button type="primary" @click="onSaveEditDialog()">
          {{ $t('common.confirm') }}
        </el-button>
      </span>
    </template>

  </el-dialog>
</template>

<script lang="ts" setup>
import { ref, reactive, onMounted } from 'vue'
import axios from 'axios'
import { ElMessage, ElMessageBox } from 'element-plus'


onMounted(() => {
  onQuery();
})

// ========================================================================
// 处理列表查询相关代码
// ========================================================================
let queryParm = reactive({
<#list fields as item >
	${item.columnName}: '',
</#list>
})

const currentPage = ref(1);  // 当前页
const pageSize = ref(5);     // 每页记录条数
const totalRow = ref(0);     // 总行数（查询接口将返回）

const isSelectedRow = ref(false);  // 是否选择了一行数据
let currentSelectRow = reactive({});  // 当前选中行的数据[-1：未选择行]

let tableData = reactive([])
// 每页显示数量【下拉列表，若显示则有】变化，触发事件
function handleSizeChange(value: number) {
  currentPage.value = 1;
  pageSize.value = value;
  onQuery();
}

// 切换当前页触发事件
function handleCurrentChange(value: number) {
  currentPage.value = value;
  onQuery();
}

// 查询数据
function onQuery() {
  var inParm = {
    'current': currentPage.value,
    'size': pageSize.value,
    'isDownExcel': '0'
  };
  for (let key in queryParm) {
    if (queryParm[key] == null || queryParm[key] == "") {
      continue;
    }
    inParm[key] = queryParm[key];
  }
  
  axios.post("/api${parm.interfacePrefix}list", inParm).then(res => {
      if (res.data.code == "200") {
        //请添加执行成功后的业务代码 
        if (res.data != null && res.data.success) {
          currentPage.value = res.data.data.page.current;
          pageSize.value = res.data.data.page.size;
          totalRow.value = res.data.data.page.total;

          //清空数组
          isSelectedRow.value = false;
          currentSelectRow = {};  // 清空当前选中行
          tableData.length = 0;

          for (var i = 0; i < res.data.data.list.length; i++) {
            tableData.push(res.data.data.list[i]);
          }
        }
      } else {
        // 错误消息为：res.data.msg 
        // 请添加执行失败后的业务代码 
      }
    });
}

/**
 *  选中一行
 * */
const handleTableSelectRow = (currentRow: any, oldCurrentRow: any) => {
  isSelectedRow.value = true;
  currentSelectRow = currentRow;
}


// ========================================================================
// 处理新增与修改弹窗相关代码
// ========================================================================
import editDialog from './${parm.pagePrefix}Edit.vue'
const editDialogVisible = ref(false);
const editDialogTitle = ref('');
const editDialogInstance = ref(null);

// 编辑窗口的操作命令
let editDialogOptCmd = reactive({
  type: 'new',
  data: {}
});


// 新增
function onAdd(title: string) {
  editDialogOptCmd.type = "new"; // 当前修改行数据设置为null，表明为新增
  editDialogOptCmd.data = {};

  editDialogTitle.value = title;
  editDialogVisible.value = true;
}

// 修改
function onModify(title: string) {
  if (!isSelectedRow.value) {
    return;
  }

  editDialogOptCmd.type = 'modify'
  editDialogOptCmd.data = currentSelectRow; // 当前修改行数据设置为选中行数据，表明为修改

  editDialogTitle.value = title;
  editDialogVisible.value = true;
}

// 删除
function onDelete() {
  ElMessageBox.confirm(
    '数据删除后将不可恢复，您确认要删除指定的数据吗？',
    '警告',
    {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning',
    }
  )
    .then(() => {

      axios.post("/api${parm.interfacePrefix}delete",
        {
<#list fields as item >
	<#if item.isPk == '1'>
          '${item.columnName}': currentSelectRow.${item.columnName}
    </#if>
</#list>
        }).then(res => {
          if (res.data.code == "200") {

            // 请添加执行成功后的业务代码 
            if (currentPage.value > 1 && tableData.length <= 1) {
              // 处理翻页后仅一条的情况
              currentPage.value = currentPage.value - 1;
            }
            onQuery();

            ElMessage({
              type: 'success',
              message: '删除成功',
            })
          } else {
            ElMessage({
              type: 'error',
              message: '删除失败，错误信息为：' + res.data.msg,
            })

            // 错误消息为：res.data.msg 
            // 请添加执行失败后的业务代码 
          }
        });


    })
}

// 导出Excel文件
function onExportExcelFile() {
	var inParm = {
	    'current': 1,
	    'size': 1000000,
	    'isDownExcel': '1'
	  };
	for (let key in queryParm) {
	    if (queryParm[key] == null || queryParm[key] == "") {
	      continue;
	    }
	    inParm[key] = queryParm[key];
	}
    axios.post("/api${parm.interfacePrefix}list",inParm , { responseType: 'blob' }).then(res => {
      const filename = res.headers["content-disposition"];
      const blob = new Blob([res.data]);
      var downloadElement = document.createElement("a");
      var href = window.URL.createObjectURL(blob);
      downloadElement.href = href;
      downloadElement.download = decodeURIComponent(filename.split("filename")[1].substring(1, filename.split("filename")[1].length));
      document.body.appendChild(downloadElement);
      downloadElement.click();
      document.body.removeChild(downloadElement);
      window.URL.revokeObjectURL(href);
    })
}

// 确认按钮-单击-调用确认方法
function onSaveEditDialog() {
  var ref = editDialogInstance.value.confirm(() => {
    editDialogVisible.value = false;
    onQuery();
  });
}

// 关闭按钮-单击-调用子页面方法后关闭
const editDialogHandleClose = (done: () => void) => {
  if (editDialogInstance.value.beforClose == null) {
    done();
    return;
  }
  editDialogInstance.value.beforClose(() => {
    done();
  });
}

</script>

<style>
.dataArea {
  height: calc(100vh - 280px);
}

.paginationArea {
  margin-top: 8px;
  float: right;
}
</style>